import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { fetchSearchLogList } from '@/business/services/search/search';
import { cancelOperateDemand, fetchDemandList, operateCancelCollect, operateCollect, operateDemand } from '@/business/services/demand/demand';
import { RequestFunction2, RequestFunction3 } from '../demand/demandList';

/**
 * @description 搜索列表
 * @author Shawn
 */

type RequestFunction = (
  pageParams: PageParams,
  keyWord?: string,
  tag?: string,
  isAppend?: boolean,
) => Promise<void>;

type RequestFunction1 = (tag: string) => Promise<void>;

type State = {
  // 搜索列表
  searchList: any[];
  // 搜索日志
  searchLogList: any[];
  // 分页信息
  pageInfo: PageInfo;
  // 数据是否加载完成
  isDataLoaded: boolean;
  // 是否有更多数据
  hasMore: boolean;
};

type Actions = {
  // 获取需求列表
  getSearchList: RequestFunction;
  // 获取搜索日志
  getSearchLogList: RequestFunction1;
  // 上拉加载
  handlePullUp: RequestFunction;
  // 下拉刷新
  handlePullDown: RequestFunction;
  // 点赞、点踩
  handleLikeOrDislike: RequestFunction2;
  // 取消点赞、点踩
  handleCancelLikeOrDislike: RequestFunction2;
  // 收藏
  handleCollect: RequestFunction2;
  // 取消收藏
  handleCancelCollect: RequestFunction3;
  clearSearch: () => void;
};

const initialState: State = {
  // 搜索列表
  searchList: [],
  // 搜索日志
  searchLogList: [],
  // 分页信息
  pageInfo: {},
  // 数据是否加载完成
  isDataLoaded: true,
  // 是否有更多数据
  hasMore: true,
};

export const searchStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取搜索列表
     * @param pageParams 分页
     * @param isAppend 是否追加数据（用于上拉加载）
     * @param keyWord 搜索关键词
     * @param tag 搜索类型
     */
    getSearchList: async (
      pageParams: PageParams,
      keyWord?: string,
      tag?: string,
      isAppend = false,
    ) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        Taro.showLoading({
          title: '搜索中',
        });
        const requestData = {
          ...pageParams,
          ...(keyWord ? { keyWord } : {}),
          ...(tag ? { tag } : {}),
        };
        console.log(requestData, 'requestData')
        const result = await fetchDemandList(requestData);
        if (result.success) {
          set((state) => {
            if (isAppend) {
              state.searchList = [...state.searchList, ...result?.data];
            } else {
              state.searchList = result?.data;
            }
            state.pageInfo = {
              pageIndex: result?.current,
              pageSize: result?.pageSize,
              totalCount: result?.totalCount,
            };
            state.hasMore = result?.current * result?.pageSize < result?.totalCount;
          });
        }
        return result
      } catch (error) {
        console.log(error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    /**
     * 上拉加载
     * @param pageParams 分页
     */
    handlePullUp: async (pageParams: PageParams, keyWord?: string, tag?: string) => {
      const newPageInfo = { ...pageParams, current: Number(pageParams.current) + 1 };
      return await get().getSearchList(newPageInfo, keyWord, tag, true);
    },

    /**
     * 下拉刷新
     * @param pageInfo 分页
     */
    handlePullDown: async (pageParams: PageParams, keyWord?: string, tag?: string) => {
      const newPageInfo = { ...pageParams };
      await get().getSearchList(newPageInfo, keyWord, tag, false);
    },

    /**
     * 获取搜索日志
     */
    getSearchLogList: async (type: string) => {
      try {
        const requestData: { type?: string } = {
        };
        if (type) {
          requestData.type = type
        }
        const result = await fetchSearchLogList(requestData);
        if (result.success) {
          set((state) => {
            state.searchLogList = result?.data;
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleLikeOrDislike: async (demandId: string, type: string, status: string) => {
      try {
        const result = await operateDemand({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.searchList.find((d) => d.id === demandId);
            if (item) {
              if (type === 'LIKE') {
                // 如果之前点踩了，先取消点踩
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                // 如果之前点赞了，先取消点赞
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleCancelLikeOrDislike: async (demandId: string, type: string, status: string) => {
      console.log('handleCancelLikeOrDislike', demandId, type, status);
      try {
        const result = await cancelOperateDemand({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.searchList.find((d) => d.id === demandId);
            if (item) {
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 收藏
     */
    handleCollect: async (demandId: string, type: string, status: string) => {
      try {
        const result = await operateCollect({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.searchList.find((d) => d.id === demandId);
            if (item) {
              if (type === 'COLLECT' || type === 'collection') {
                item.collectCount = (item.collectCount || 0) + 1;
                item.collect = true;
              }
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消收藏
     */
    handleCancelCollect: async (demandId: string) => {
      try {
        const result = await operateCancelCollect({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.searchList.find((d) => d.id === demandId);
            if (item) {
              item.collectCount = (item.collectCount || 0) - 1;
              item.collect = false;
              console.log('handleCancelCollect success');
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    clearSearch: async () => {
      set((state) => {
        state.searchLogList = []
        state.pageInfo = {}
        state.searchList = []
        state.isDataLoaded = true
        state.hasMore = true
      })
    }
  })),
);
